<script setup>
import { ref, reactive, onMounted, onUnmounted} from 'vue';
import axios from 'axios';
import Modal from '@/components/Modal.vue'; // 导入 Modal 组件
import { Plus, Comment } from '@element-plus/icons-vue'
import CustomUpload from '@/components/CustomUpload.vue';
import { DeleteFilled } from '@element-plus/icons-vue';
import { ElMessageBox } from 'element-plus'; // 确保导入正确的组件
import { userId } from '@/stores/user'


const posts = ref([]); // 帖子列表
const newPostContent = ref(''); // 新帖子内容
const newPostImages = ref([]); // 新帖子图片
const isModalOpen = ref(false); // 弹窗状态
const basePath = ref("https://47.120.69.214:8787/"); // 基本路径
const userList = ref([]); // 用户列表
const customUploadRef = ref(null);
const socket = ref(null);
const user = userId; // 当前用户 这里的user是假设的，实际上应该从登录状态中获取
const visible = reactive({}) // 删除弹窗状态
const post = {theSame: true}; // 帖子对象
const URL = window.URL || window.webkitURL;
const temple =ref(null);

const fetchPosts = async () => {
  try {
    const response = await axios.get('https://47.120.69.214:8787/twitter/getTwitterOfFriends', {
      params: {
        current: 1,
        size: 50,
        userId: user.value
      }
    });
    const postsData = response.data;

    const postsWithComments = await Promise.all(postsData.map(async (post) => {
      const authorInfo = getAvatarInfo(post.userId);
      const commentInformationList = await fetchCommentInformation(post.id);
      const thumbsUpResponse = await axios.get('https://47.120.69.214:8787/twitterComment/getByTwitterId', {
        params: {
          twitterId: post.id
        }
      });
      const thumbsUpData = thumbsUpResponse.data;

      const thumbsUpUserIdList = thumbsUpData.thumbsUpUserIdList || []; // 确保 thumbsUpUserIdList 不为 undefined

      const currentUser = userList.value.find(u => u.id === user.value);

      const theSame = ref(false);

      if (user.value === post.userId) {
        theSame.value = true;
      }

      const currentUserName = currentUser ? currentUser.name : '当前用户';
      const publishtime = new Date(post.publishTime).toLocaleString();
      const hasLiked = thumbsUpUserIdList.includes(user.value); // 使用 thumbsUpUserIdList 检查当前用户是否已经点赞

      return {
        ...post,
        avatar: authorInfo.headShotUrl,
        author: authorInfo.name,
        comments: commentInformationList.map(comment => ({
          userName: comment.commentUserName,
          content: comment.content,
          id: comment.commentId,
          publishtime: new Date(comment.publishTime).toLocaleString()
        })),
        thumbsUpUserList: thumbsUpData.thumbsUpUserList || [], // 确保 thumbsUpUserList 不为 undefined
        thumbsUpUserIdList: thumbsUpUserIdList,
        liked: hasLiked,
        showComments: false,
        publishtime: publishtime,
        theSame: theSame.value
      };
    }));

    posts.value = postsWithComments;
  } catch (error) {
    console.error('Error fetching posts:', error);
  }
};



const fetchUserList = async () => { // 获取用户列表
  try {
    const response = await axios.get('https://47.120.69.214:8787/user/getAll');
    userList.value = response.data;
    // console.log('用户列表数据:', userList.value); // 用于确认用户列表数据
  } catch (error) {
    console.error('Error fetching user list:', error);
  }
};

const getAvatarInfo = (userId) => { // 获取头像信息
  const user = userList.value.find(u => u.id === userId);
  if (user) {
    return {
      avatar: user.headShotUrl,
      name: user.name
    };
  } else return {
    avatar: '',
    name: ''
  };
};

const addPost = async () => { 
  customUploadRef.value.emitSelectedImages();
  if (newPostContent.value.trim() !== '' || newPostImages.value.length > 0) { 
    const formData = new FormData();
    formData.append('content', newPostContent.value);
    newPostImages.value.forEach((image, index) => {
      formData.append('pictures', image);
      // console.log(image);
    });
    formData.append('userId', user.value); 
    try {
      const response = await axios.post('https://47.120.69.214:8787/twitter/add', formData, { 
        headers: {
          'Content-Type': 'multipart/form-data' 
        }
      });
      if (response.status === 200) { 
        // console.log('Post added successfully');
        // console.log(posts.value)
        const newPost = { 
          content: newPostContent.value,
          author: '当前用户',
          avatar: newPostImages.value[0] || '',
          pictureURLList: newPostImages.value.map(image => image.name), 
          time: '刚刚', 
          images: [], 
          liked: false,
          showComments: false, 
          newComment: '', 
          comments: [], 
          theSame: true 
        };
        posts.value.unshift(newPost); 

        // 清空保存的内容和图片
        localStorage.removeItem('savedPostContent');
        localStorage.removeItem('savedPostImages');

        newPostContent.value = ''; 
        newPostImages.value = []; 

        newPostImages.value.forEach((image) => { 
          const reader = new FileReader(); 
          reader.onload = (e) => { 
            newPost.images.push(e.target.result); 
          };
          reader.readAsDataURL(image); 
        });

        setTimeout(() => { 
          closeModal();
        }, 500); 
        fetchPosts();
      }
    } catch (error) {
      console.error('Error adding post:', error);
    }
  } else {
    alert('请输入文字或选择图片');
  }
};






// const emit = defineEmits(['imagesSelected']);



// const emitSelectedImages = () => {
//   emit('imagesSelected', newPostImages.value);
//   console.log('Emitted selected images:22222', newPostImages.value);
// }





const saveContent = () => {
  // console.log('Saving content...');
  // console.log('newPostContent:', newPostContent.value);
  // console.log('newPostImages before saving:', newPostImages.value); // 添加这行日志

  // 调用 customUploadRef 的 emitSelectedImages 方法以更新 newPostImages 列表
  customUploadRef.value.emitSelectedImages();

  // 检查图片列表是否为空
  if (newPostImages.value.length === 0) {
    ElMessageBox.confirm('图片列表为空，确定要保存吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      // 用户点击了确认按钮，继续执行保存操作
      performSaveContent();
    }).catch(() => {
      // 用户点击了取消按钮，终止保存操作
      console.log('用户取消了保存操作');
    });
  } else {
    // 图片列表不为空，直接执行保存操作
    performSaveContent();
  }
};

const performSaveContent = () => {
  // console.log('Performing save content...');
  // console.log('newPostContent:', newPostContent.value);
  // console.log('newPostImages before saving:', newPostImages.value); // 添加这行日志

  // 检查 localStorage 是否可用
  if (typeof Storage === "undefined") {
    console.error("Sorry, your browser does not support Web Storage...");
    return;
  }

  // 保存内容
  try {
    localStorage.setItem('savedPostContent', newPostContent.value || '');
  } catch (error) {
    console.error('Error saving content to localStorage:', error);
  }

  // 保存图片
  if (newPostImages.value && newPostImages.value.length > 0) {
    const images = newPostImages.value.map(image => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => resolve(e.target.result);
        reader.onerror = (e) => reject(e);
        reader.readAsDataURL(image); // 将图片转换为 Base64 编码
      });
    });

    Promise.all(images).then((base64Images) => {
      try {
        localStorage.setItem('savedPostImages', JSON.stringify(base64Images));
        console.log('Content saved successfully');
        closeModal();
      } catch (error) {
        console.error('Error saving images to localStorage:', error);
      }
    }).catch((error) => {
      console.error('Error converting images to Base64:', error);
    });
  } else {
    try {
      localStorage.setItem('savedPostImages', JSON.stringify([]));
      // console.log('Content saved successfully');
      closeModal();
    } catch (error) {
      console.error('Error saving images to localStorage:', error);
    }
  }
};



const openModal = () => {
  // console.log('openModal called');
  isModalOpen.value = true;

  // 读取保存的内容
  const savedContent = localStorage.getItem('savedPostContent');
  if (savedContent) {
    newPostContent.value = savedContent;
  }

  // 读取保存的图片
  const savedImages = localStorage.getItem('savedPostImages');
  if (savedImages) {
    // console.log('savedImages:', savedImages);
    const base64Images = JSON.parse(savedImages);
    newPostImages.value = base64Images.map((base64Image, index) => {
      const blob = dataURLtoBlob(base64Image);
      return new File([blob], `image_${index}.png`, { type: 'image/png' });
    });
  } else {
    // console.log('savedImages is null or undefined');
  }

  // console.log('newPostImages after opening modal:', newPostImages.value); // 添加这行日志
}




const closeModal = () => { // 关闭弹窗
  isModalOpen.value = false;
};

onMounted(() => { // 页面加载完成后获取帖子列表
  fetchUserList();
  fetchPosts();
  // connectWebSocket();
});

const toggleLike = async (post) => { // 切换点赞状态
  try {
    const currentUser = userList.value.find(u => u.id === user.value); // 获取当前用户
    const currentUserName = currentUser ? currentUser.name : '当前用户'; // 获取当前用户的用户名

    // 检查当前用户是否在点赞用户列表中
    const hasLiked = post.thumbsUpUserList.includes(currentUserName);

    if (hasLiked) {
      // 如果当前用户已经点赞，则调用取消点赞接口
      const response = await axios.get('https://47.120.69.214:8787/twitterComment/thumbsDownForTwitter', {
        params: {
          twitterId: post.id,
          userId: user.value // 假设当前用户ID为13
        }
      });

      if (response.status === 200) {
        // console.log('Server response:', response.data); // 添加日志
        post.liked = !post.liked;
        const index = post.thumbsUpUserList.indexOf(currentUserName);
        if (index > -1) {
          post.thumbsUpUserList.splice(index, 1); // 移除当前用户的用户名
        }
      }
    } else {
      // 如果当前用户未点赞，则调用点赞接口
      const response = await axios.get('https://47.120.69.214:8787/twitterComment/thumbsUpForTwitter', {
        params: {
          twitterId: post.id,
          userId: user.value // 假设当前用户ID为13
        }
      });

      if (response.status === 200) {
        // console.log('Server response:', response.data); // 添加日志
        post.liked = !post.liked;
        post.thumbsUpUserList.push(currentUserName); // 添加当前用户的用户名
      }
    }
  } catch (error) {
    console.error('Error toggling like:', error);
  }
};

const toggleComment = async (post) => {// 切换评论状态
  post.showComments = !post.showComments;

  // 获取评论信息
  const commentInformationList = await fetchCommentInformation(post.id);
  // console.log(commentInformationList);
  // 更新评论列表
  post.comments = commentInformationList.map(comment => ({
    userName: comment.commentUserName,
    content: comment.content,
    id: comment.commentId, // 确保包含 id 属性
    publishtime: new Date(comment.publishTime).toLocaleString()
  }));
};

const fetchCommentInformation = async (twitterId) => {
  try {
    const response = await axios.get('https://47.120.69.214:8787/twitterComment/getByTwitterId', {
      params: {
        twitterId
      }
    });
    if (response.status === 200) {
      // console.log('Comment information fetched successfully');
      // console.log('Comment content:'); // 打印评论内容
      
      return response.data.commentInformationList;
    }
  } catch (error) {
    console.error('Error fetching comment information:', error);
    return [];
  }
};


const addCommentToTwitter = async (twitterId, userId, comment) => {
  try {
    const response = await axios.get('https://47.120.69.214:8787/twitterComment/commentForTwitter', {
      params: {
        comment,
        twitterId,
        userId
      }
    });
    if (response.status === 200) {
      // console.log('Comment added successfully');
      // console.log('Comment content:', comment); // 打印评论内容
      return true;   // return response.data.commentId; // 
    }
  } catch (error) {
    console.error('Error adding comment:', error);
    return false;
  }
};


const addComment = async (post) => {
  if (post.newComment.trim() !== '') {
    const commentId = await addCommentToTwitter(post.id, user.value, post.newComment); // 假设当前用户ID为13
    if (commentId) {
      const currentUser = userList.value.find(u => u.id === user.value); // 获取当前用户
      const currentUserName = currentUser ? currentUser.name : '当前用户'; // 获取当前用户的用户名
      post.comments.push({
        userName: currentUserName,
        content: post.newComment,
        id: commentId, // 保存评论ID
        userId: user.value // 保存评论用户的ID
      });
      post.newComment = '';
      // 重新获取评论数据
      const commentInformationList = await fetchCommentInformation(post.id);
      post.comments = commentInformationList.map(comment => ({
        userName: comment.commentUserName,
        content: comment.content,
        id: comment.commentId,
        userId: comment.userId
      }));
    }
  }
};

const dataURLtoBlob = (dataURL) => {
  const arr = dataURL.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}


const deleteComment = async (post, index, commentId) => {
  setTimeout(async () => {
    try {
      // console.log(`Deleting comment with ID ${commentId}`);

      // 调用删除评论的接口
      const response = await axios.get('https://47.120.69.214:8787/twitterComment/deleteComment', {
        params: {
          commentId: commentId
        }
      });

      if (response.status === 200) {
        console.log('Comment deleted successfully');

        // 本地删除评论
        post.comments.splice(index, 1);

        // 重新获取评论信息
        const commentInformationList = await fetchCommentInformation(post.id);


        // 更新本地评论列表
        post.comments = commentInformationList.map(comment => ({
          userName: comment.commentUserName,
          content: comment.content,
          id: comment.commentId
        }));
      }
    } catch (error) {
      console.error('Error deleting comment:', error);
    }
  }, 100); // 延迟100毫秒
};

const handleImagesSelected = (images) => { // 处理图片选择
  // console.log('Selected images:', images);
  newPostImages.value = images;
};

const deletePost = async (postId) => {// 删除朋友圈
  try {
    const response = await axios.get('https://47.120.69.214:8787/twitter/delete', {
      params: {
        twitterId: postId
      }
    });

    if (response.status === 200) {
      console.log('朋友圈删除成功');
      // 从本地帖子列表中移除该帖子
      posts.value = posts.value.filter(post => post.id !== postId);
    } else {
      console.error('删除朋友圈失败，状态码:', response.status);
    }
  } catch (error) {
    console.error('删除朋友圈时发生错误:', error);
  }
};

const confirmDelete = (post) => {
  deletePost(post.id);
  visible[post.id] = false;
};



</script>

<template>
  <div >
    <h1>朋友圈</h1>
    <button @click="openModal" class="blue-plus-button"></button>
    <Modal :show="isModalOpen" @close="closeModal">
      <div>
        <el-text class="mx-1" type="success" size="large">发布朋友圈</el-text><br><br>
        <form @submit.prevent="addPost">
          <div>
            <el-input v-model="newPostContent" placeholder="分享你的新鲜事..." style="width: 450px; height: 50px;" show-word-limit maxlength="1000"></el-input>
            <br><br>
            <CustomUpload ref="customUploadRef" @imagesSelected="handleImagesSelected" />
            <div v-for="(image, index) in newPostImages" :key="index">
              <!-- <img v-if="image" :src="URL.createObjectURL(image)" alt="Uploaded Image" /> -->
            </div>
            <el-button type="primary" native-type="submit">发布</el-button>
            <el-button type="primary" @click="saveContent">保存</el-button>
          </div>
        </form>
      </div>
    </Modal>
    <el-card v-for="post in posts" :key="post.id" class="post-card">
      <div class="post-author">
        <el-avatar :src="basePath + getAvatarInfo(post.userId).avatar" alt="头像" style="width: 30px;"></el-avatar>
        {{ post.author }}
      </div>
      <div class="post-content">{{ post.content }}</div>
      <div class="post-images">
        <el-image v-for="(image, i) in post.pictureURLList" :key="i" :src="basePath + image" alt="图片" :preview-src-list="[basePath + image]"></el-image> <!-- 照片 -->
      </div>
      <div class="post-time">{{ post.time }}</div>
      <div class="post-actions">
        <span class="action-btn" :class="{ 'liked': post.liked }" @click="toggleLike(post)">
          <img :src="post.liked ? '/img/AfterGood.png' : '/img/prepareGood.png'" alt="点赞图标" style="width: 24px; height: 24px;">&nbsp;&nbsp;
        </span>
        <span class="action-btn" @click="toggleComment(post)" style="font-size: 22px;">
          <el-icon><Comment /></el-icon>
        </span>&nbsp;&nbsp;
        <el-popover :visible="visible[post.id]" placement="top" :width="160">
          <p>您确认要删除这条朋友圈吗?</p>
          <div style="text-align: right; margin: 0">
            <el-button size="small" text @click="visible[post.id] = false">取消</el-button>
            <el-button size="small" type="primary" @click="confirmDelete(post)">确认</el-button>
          </div>
          <template #reference>
            <span @click="visible[post.id] = true" v-show="post.theSame">
              <el-icon size="21"><DeleteFilled /></el-icon>
            </span>
          </template>
        </el-popover>
        <span class="publish-time">{{ post.publishtime }}</span>
      </div>
      <div class="likes" v-if="post.thumbsUpUserList && post.thumbsUpUserList.length > 0">
        <span>点赞用户: {{ post.thumbsUpUserList.join(', ') }}</span><hr>
      </div>
      <div class="comments" v-if="post.showComments">
        <div class="comment" v-for="(comment, i) in post.comments" :key="i">&nbsp;
          <span>{{ comment.userName }}: {{ comment.content }}</span>
          <el-button v-if="post.theSame" @click="deleteComment(post, i, comment.id)">删除</el-button>
        </div>
        <el-input v-model="post.newComment" placeholder="发送评论" style="width: 655px; height: 30px;" 
        :autosize="{ minRows: 1, maxRows: 100 }" type="textarea" show-word-limit maxlength="1000"></el-input>
        <el-button @click="addComment(post)">发送</el-button>
      </div>
    </el-card>
  </div>
</template>

<style>
body {  
  /* max-width: 800px; */
  /* margin:0;
  padding:0; */
  /* margin: 0 auto; */
  /* padding: 20px; */
  font-family: Arial, sans-serif;
}

.post-card {
  width:60vw;
  /* height:40vh; */
  left:20%;
  margin-bottom: 20px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f9f9f9;
  position: relative;
  transition: transform 0.3s, box-shadow 0.3s;
}

.post-card:hover {
  transform: scale(1.02);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.post-content {
  margin-bottom: 10px;
}

.post-author {
  display: flex;
  align-items: center;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.post-author .el-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 10px;
}

.post-time {
  font-size: 12px;
  color: #888;
}

.post-images {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
}

.post-images .el-image {
  /* width: calc(33.33% - 10px); */
  width:10vw;
  margin-right: 10px;
  margin-bottom: 10px;
}

.post-actions {
  margin-top: 10px;
}

.action-btn {
  cursor: pointer;
  margin-right: 10px;
  color: #888;
  transition: color 0.3s;
}

.action-btn:hover {
  color: #333;
}

.liked {
  color: red;
  animation: heartbeat 0.5s ease-in-out;
}

@keyframes heartbeat {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

.comments {
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  background-color: #f0f0f0;
}

.comment {
  margin-bottom: 5px;
}

.comment .el-button {
  margin-left: 5px;
}

.blue-plus-button {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #409EFF;
  position: fixed;
  margin-left: 40%;

  margin-top: -10px;
  transition: transform 0.3s;
}

.blue-plus-button:hover {
  transform: scale(1.1);
}

.blue-plus-button::before,
.blue-plus-button::after {
  content: '';
  position: absolute;
  background-color: white;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.blue-plus-button::before {
  width: 2px;
  height: 14px;
}

.blue-plus-button::after {
  width: 14px;
  height: 2px;
}

.publish-time {
  position: absolute;
  margin-right: 10px;
  top: 10px;
  right: 10px;
  font-size: 16px;
  color: #888;
}
</style>